<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的刷题小程序</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- SQL.js 已替换为 Node.js + sqlite3 后端 -->
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <div id="app">
        <header>
            <div class="container header-content">
                <div class="logo">
                    <i class="fa fa-graduation-cap"></i>
                    <span>我的刷题小程序</span>
                </div>
                <nav>
                    <ul>
                        <li><a :class="{ active: currentView === 'quiz' }" @click="() => changeView('quiz')"><i class="fa fa-play-circle"></i> 开始刷题</a></li>
                        <li><a :class="{ active: currentView === 'manage' }" @click="() => changeView('manage')"><i class="fa fa-list-alt"></i> 题目管理</a></li>
                        <li><a :class="{ active: currentView === 'import' }" @click="() => changeView('import')"><i class="fa fa-upload"></i> 导入导出</a></li>
                        <li><a :class="{ active: currentView === 'settings' }" @click="() => changeView('settings')"><i class="fa fa-cog"></i> 设置</a></li>
                    </ul>
                </nav>
            </div>
        </header>
        
        <main class="container">
            <!-- 错误提示区域 -->
            <div v-if="errorMessage" class="error-log">
                <strong>系统提示:</strong> {{ errorMessage }}
            </div>
            
            <!-- 刷题视图 -->
            <div v-if="currentView === 'quiz'" class="quiz-container">
                <div class="card">
                    <div class="card-title">
                        <i class="fa fa-question-circle"></i> 随机刷题
                    </div>
                    
                    <div class="progress-container" >
                        <div class="progress-bar" >
                            <div class="progress" :style="{ width: (currentQuestionIndex / totalQuestions) * 100 + '%' }"></div>
                        </div>
                        <div style="text-align: right; margin-top: 5px; font-size: 0.9rem;">
                            {{ currentQuestionIndex + 1 }} / {{ totalQuestions }}
                        </div>
                    </div>

                     <div v-if="totalQuestions === 0" class="empty-state">
                        <p style="text-align: center; padding: 20px;">暂时还没有题目，快点去创建题目吧！</p>
                        <div style="text-align: center;">
                            <button class="btn btn-primary" @click="() => changeView('manage')">
                                <i class="fa fa-plus"></i> 添加题目
                            </button>
                        </div>
                    </div>

                    <div v-else-if="currentQuestion" class="question">
                        <div class="question-text">
                            <span v-if="currentQuestion.type" class="question-type">{{ currentQuestion.type === 'multiple' ? '多选题' : '单选题' }}</span>
                            {{ currentQuestionIndex + 1 }}. {{ currentQuestion.question }}
                        </div>
                        
                        <div class="options">
                            <div 
                            v-for="(option, index) in currentQuestion.options" 
                            :key="index"
                            class="option"
                            :class="{ 
                                selected: isOptionSelected(index),
                                correct: showAnswer && isCorrectAnswer(index),
                                incorrect: showAnswer && isOptionSelected(index) && !isCorrectAnswer(index)
                            }"
                            @click="selectOption(index)"
                        >
                            {{ String.fromCharCode(65 + index) }}. {{ option }}
                        </div>
                        </div>
                        
                        <div v-if="showAnswer" class="answer-explanation">
                            <strong>答案解析：</strong> {{ currentQuestion.explanation || '无解析' }}
                        </div>
                    </div>
                                                    
                    <div v-else>
                        <p style="text-align: center; padding: 20px;">加载题目中...</p>
                    </div>
                    
                    <div class="action-buttons" :style="{ display: totalQuestions === 0 ? 'none' : 'flex' }">
                        <button 
                            class="btn btn-outline"
                            @click="prevQuestion"
                            :disabled="currentQuestionIndex === 0"
                        >
                            <i class="fa fa-arrow-left"></i> 上一题
                        </button>
                        
                        <div v-if="!showAnswer">
                            <button 
                                class="btn btn-danger" 
                                @click="deleteAndNextQuestion"
                            >
                                <i class="fa fa-trash"></i> 删除题目
                            </button>
                            <button 
                                class="btn btn-primary" 
                                @click="handleSubmit"
                                :disabled="!canSubmit()"
                            >
                                <i class="fa fa-check"></i> 
                                {{ answerMode === 'immediate' ? '查看答案' : '提交答案' }}
                            </button>
                        </div>
                        
                        <div v-else>
                            <button 
                                class="btn btn-danger" 
                                @click="deleteAndNextQuestion"
                            >
                                <i class="fa fa-trash"></i> 删除题目
                            </button>
                            <button 
                                class="btn btn-primary" 
                                @click="nextQuestion"
                                :disabled="currentQuestionIndex === totalQuestions - 1"
                            >
                                <i class="fa fa-arrow-right"></i> 下一题
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 题目管理视图 -->
            <div v-if="currentView === 'manage'">
                <div class="card">
                    <div class="card-title">
                        <i class="fa fa-list-alt"></i> 题目管理
                    </div>
                    
                    <div style="margin-bottom: 20px; text-align: right;">
                        <button class="btn btn-primary" @click="openAddQuestionModal">
                            <i class="fa fa-plus"></i> 添加题目
                        </button>
                    </div>
                    
                    <div class="stats">
                        <div class="stat-item">
                            <div class="stat-value">{{ totalQuestions }}</div>
                            <div class="stat-label">总题数</div>
                        </div>
                        <div class="stat-item">
                            <div class="stat-value">{{ getTotalWrongCount() }}</div>
                            <div class="stat-label">总错误次数</div>
                        </div>
                        <div class="stat-item">
                            <div class="stat-value">{{ getHardQuestionsCount() }}</div>
                            <div class="stat-label">易错题 (≥3次错)</div>
                        </div>
                        <div class="stat-item">
                            <div class="stat-value">{{ getTotalAttemptCount() }}</div>
                            <div class="stat-label">总做题次数</div>
                        </div>
                    </div>
                    
                    <div class="table-container">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>序号</th>
                                    <th>题目</th>
                                    <th>题型</th>
                                    <th>错误次数</th>
                                    <th>做题次数</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr v-for="(question, index) in paginatedQuestions" :key="question.id">
                                    <td>{{ (currentPage - 1) * pageSize + index + 1 }}</td>
                                    <td>{{ question.question.length > 50 ? question.question.substring(0, 50) + '...' : question.question }}</td>
                                    <td>
                                        <span class="badge badge-type">
                                            {{ question.type === 'multiple' ? '多选题' : '单选题' }}
                                        </span>
                                    </td>
                                    <td>
                                        <span :class="{'badge badge-danger': question.wrongCount >= 3}">
                                            {{ question.wrongCount }}
                                        </span>
                                    </td>
                                    <td>
                                        <span class="badge badge-info">
                                            {{ question.attemptCount || 0 }}
                                        </span>
                                    </td>
                                    <td class="table-actions">
                                        <button class="btn btn-outline" @click="() => openEditQuestionModal(question)">
                                            <i class="fa fa-edit"></i> 编辑
                                        </button>
                                        <button class="btn btn-danger" @click="() => handleDeleteQuestion(question.id)">
                                            <i class="fa fa-trash"></i> 删除
                                        </button>
                                    </td>
                                </tr>
                                <tr v-if="questions.length === 0">
                                    <td colspan="5" style="text-align: center; padding: 20px;">暂无题目数据</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <!-- 分页控件 -->
                    <div class="pagination" v-if="totalPages > 1">
                        <button class="btn btn-outline" @click="prevPage" :disabled="currentPage === 1">上一页</button>
                        <span class="pagination-info">第 {{ currentPage }} / {{ totalPages }} 页</span>
                        <button class="btn btn-outline" @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
                    </div>
                </div>
            </div>
            
            <!-- 导入导出视图 -->
            <div v-if="currentView === 'import'">
                <div class="grid">
                    <div class="card">
                        <div class="card-title">
                            <i class="fa fa-upload"></i> 批量导入题目
                        </div>
                        
                        <div class="file-upload" @click="triggerFileUpload">
                            <i class="fa fa-file-text-o" style="font-size: 3rem; color: var(--vue-green); margin-bottom: 10px;"></i>
                            <p>点击或拖拽文件到此处上传</p>
                            <p style="font-size: 0.8rem; color: var(--text-light); margin-top: 5px;">支持 CSV 或 TXT 格式</p>
                            <input type="file" id="file-upload" @change="handleFileUpload" accept=".csv,.txt">
                        </div>
                        
                        <div class="import-template">
                            <p>
                                <i class="fa fa-info-circle"></i> 支持两种导入格式：
                            </p>
                            <p style="margin-top: 5px; font-size: 0.85rem;">
                                1. CSV格式：题目,选项A,选项B,选项C,选项D[,选项E],正确答案(字母，如A,B),解析,题型(single/multiple)
                            </p>
                            <p style="margin-top: 5px; font-size: 0.85rem;">
                                2. TXT格式：支持包含题目编号、题型、中英文题目、多个选项、答案和解析的格式
                            </p>
                            <button class="btn btn-outline" @click="downloadTemplate" style="margin-top: 10px;">
                                <i class="fa fa-download"></i> 下载CSV导入模板
                            </button>
                        </div>
                    </div>
                    
                    <div class="card">
                        <div class="card-title">
                            <i class="fa fa-download"></i> 导出题目
                        </div>
                        
                        <p style="margin-bottom: 20px;">将所有题目导出为 CSV 格式文件</p>
                        
                        <button class="btn btn-primary" @click="exportQuestions" :disabled="questions.length === 0">
                            <i class="fa fa-file-excel-o"></i> 导出全部题目
                        </button>
                        
                        <button class="btn btn-outline" style="margin-top: 10px;" @click="exportWrongQuestions" :disabled="getWrongQuestionsCount() === 0">
                            <i class="fa fa-file-excel-o"></i> 只导出错题
                        </button>
                    </div>
                </div>
            </div>
            
            <!-- 设置视图 -->
            <div v-if="currentView === 'settings'">
                <div class="card">
                    <div class="card-title">
                        <i class="fa fa-cog"></i> 系统设置
                    </div>
                    
                    <div class="settings-group">
                        <div class="settings-title">答题模式设置</div>
                        
                        <div class="radio-group">
                            <div class="radio-item">
                                <input type="radio" id="mode-immediate" v-model="answerMode" value="immediate">
                                <label for="mode-immediate">选择后立即显示答案</label>
                            </div>
                            <div class="radio-item">
                                <input type="radio" id="mode-after" v-model="answerMode" value="after">
                                <label for="mode-after">提交后统一显示答案</label>
                            </div>
                        </div>
                    </div>
                    
                    <div class="settings-group">
                        <div class="settings-title">数据管理</div>
                        
                        <button class="btn btn-danger" @click="clearAllData">
                            <i class="fa fa-trash"></i> 清空所有数据
                        </button>
                        
                        <p style="margin-top: 10px; font-size: 0.9rem; color: var(--text-light);">
                            此操作将删除所有题目和记录，且无法恢复，请谨慎操作。
                        </p>
                    </div>
                    
                    <div class="settings-group">
                        <div class="settings-title">关于</div>
                        
                        <p>智能刷题小程序 v1.0</p>
                        <p style="margin-top: 5px; color: var(--text-light);">
                            一款简单实用的本地刷题工具，帮助你高效学习和复习。
                        </p>
                    </div>
                </div>
            </div>
        </main>
        
        <!-- 添加/编辑题目模态框 -->
        <div class="modal-backdrop" :class="{ active: questionModalActive }">
            <div class="modal">
                <div class="modal-header">
                    <div class="modal-title">
                        {{ editingQuestion ? '编辑题目' : '添加新题目' }}
                    </div>
                    <button class="modal-close" @click="closeQuestionModal">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label for="questionType">题型</label>
                        <select id="questionType" v-model="formQuestion.type" required>
                            <option value="single">单选题</option>
                            <option value="multiple">多选题</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="question">题目内容</label>
                        <textarea id="question" v-model="formQuestion.question" required></textarea>
                    </div>
                    
                    <div class="form-group" v-for="(option, index) in formQuestion.options" :key="index">
                        <label :for="'option' + String.fromCharCode(65 + index)">选项 {{ String.fromCharCode(65 + index) }}</label>
                        <input 
                            type="text" 
                            :id="'option' + String.fromCharCode(65 + index)" 
                            v-model="formQuestion.options[index]" 
                            required
                        >
                    </div>
                    
                    <div class="form-group">
                        <button class="btn btn-outline" @click="addOption" :disabled="formQuestion.options.length >= 6">
                            <i class="fa fa-plus"></i> 添加选项
                        </button>
                        <button class="btn btn-outline" @click="removeOption" :disabled="formQuestion.options.length <= 2" style="margin-left: 10px;">
                            <i class="fa fa-minus"></i> 移除选项
                        </button>
                    </div>
                    
                    <div class="form-group">
                        <label for="correctAnswer">正确答案</label>
                        <div v-if="formQuestion.type === 'single'">
                            <select id="correctAnswer" v-model="formQuestion.correctAnswer[0]" required>
                                <option v-for="(option, index) in formQuestion.options" :value="index">
                                    {{ String.fromCharCode(65 + index) }}
                                </option>
                            </select>
                        </div>
                        <div v-if="formQuestion.type === 'multiple'">
                            <select id="correctAnswer" v-model="formQuestion.correctAnswer" multiple required>
                                <option v-for="(option, index) in formQuestion.options" :value="index">
                                    {{ String.fromCharCode(65 + index) }}
                                </option>
                            </select>
                            <p style="font-size: 0.8rem; color: var(--text-light); margin-top: 5px;">按住Ctrl键可多选</p>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="explanation">答案解析（可选）</label>
                        <textarea id="explanation" v-model="formQuestion.explanation"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-outline" @click="closeQuestionModal">取消</button>
                    <button class="btn btn-primary" @click="saveQuestion">保存</button>
                </div>
            </div>
        </div>
        
        <!-- 通知组件 -->
        <div class="notification" :class="{ active: notification.active, 'notification-success': notification.type === 'success', 'notification-error': notification.type === 'error' }">
            <i v-if="notification.type === 'success'" class="fa fa-check-circle" style="color: #00C851;"></i>
            <i v-if="notification.type === 'error'" class="fa fa-times-circle" style="color: var(--danger);"></i>
            <span>{{ notification.message }}</span>
        </div>
        
        <footer>
            <div class="container">
                <p>PMP &copy; 2025</p>
            </div>
        </footer>
    </div>

    <script>
        // 初始化SQL.js并捕获错误
        const initDB = async () => {
            try {
                // 检查浏览器是否支持WebAssembly
                if (typeof WebAssembly !== 'object' || typeof WebAssembly.instantiate !== 'function') {
                    throw new Error('您的浏览器不支持WebAssembly，无法运行此应用。请使用最新版本的Chrome、Firefox或Edge浏览器。');
                }
                
                const SQL = await initSqlJs({
                    locateFile: file => `https://cdn.jsdelivr.net/npm/sql.js@1.8.0/dist/${file}`
                });
                
                // 从localStorage加载数据库，如果不存在则创建新数据库
                let db;
                const savedDB = localStorage.getItem('quizDB');
                
                if (savedDB) {
                    try {
                        const dbBuffer = Uint8Array.from(atob(savedDB), c => c.charCodeAt(0));
                        db = new SQL.Database(dbBuffer);
                    } catch (e) {
                        console.error('加载数据库失败，创建新数据库:', e);
                        // 数据库损坏，创建新的
                        db = new SQL.Database();
                    }
                } else {
                    db = new SQL.Database();
                }
                
                // 检查表结构是否正确，确保包含options列
                try {
                    // 尝试查询options列
                    db.run("SELECT options FROM questions LIMIT 1");
                } catch (e) {
                    console.warn('表结构不匹配，重建表:', e);
                    // 表结构不匹配，删除旧表并重建
                    try {
                        db.run("DROP TABLE IF EXISTS questions");
                    } catch (dropError) {
                        console.error('删除旧表失败:', dropError);
                    }
                    // 创建新表
                    db.run(`
                        CREATE TABLE questions (
                            id INTEGER PRIMARY KEY AUTOINCREMENT,
                            question TEXT NOT NULL,
                            options TEXT NOT NULL, -- 存储JSON数组
                            correctAnswer TEXT NOT NULL, -- 存储JSON数组
                            explanation TEXT,
                            wrongCount INTEGER DEFAULT 0,
                            type TEXT DEFAULT 'single',
                            createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                        )
                    `);
                }
                
                return db;
            } catch (error) {
                console.error('初始化数据库失败:', error);
                throw error; // 抛出错误以便上层处理
            }
        };
        
        // 保存数据库到localStorage
        const saveDB = (db) => {
            try {
                const data = db.export();
                const base64Data = btoa(String.fromCharCode(...new Uint8Array(data)));
                localStorage.setItem('quizDB', base64Data);
            } catch (error) {
                console.error('保存数据库失败:', error);
                throw error;
            }
        };
        
        // 主应用
        const { createApp } = Vue;
        
        createApp({
            data() {
                return {
                    currentView: 'quiz', // 默认显示刷题视图
                    db: null,
                    questions: [],
                    shuffledQuestions: [],
                    currentQuestionIndex: 0,
                    currentQuestion: null,
                    userAnswer: [], // 数组，支持多选题
                    showAnswer: false,
                    answerMode: localStorage.getItem('answerMode') || 'immediate',
                    
                    // 模态框状态
                    questionModalActive: false,
                    editingQuestion: null,
                    formQuestion: {
                        type: 'single', // single 或 multiple
                        question: '',
                        options: ['', '', '', '', ''], // 默认5个选项，支持动态增减
                        correctAnswer: [], // 数组，支持多选题
                        explanation: ''
                    },
                    
                    // 通知
                    notification: {
                        active: false,
                        message: '',
                        type: 'success' // success 或 error
                    },
                    
                    // 错误信息
                    errorMessage: ''
                };
            },
            
            computed: {
                totalQuestions() {
                    return this.questions.length;
                }
            },
            
            async created() {
                try {
                    // 初始化数据库
                    this.db = await initDB();
                    // 加载题目
                    this.loadQuestions();
                } catch (error) {
                    console.error('应用初始化失败:', error);
                    this.errorMessage = error.message || '应用初始化失败，请刷新页面重试。';
                }
            },
            
            methods: {
                // 切换视图
                changeView(viewName) {
                    try {
                        this.currentView = viewName;
                    } catch (error) {
                        console.error('切换视图失败:', error);
                        this.showNotification('切换视图失败: ' + error.message, 'error');
                    }
                },
                
                // 加载所有题目
                loadQuestions() {
                    console.log('loadQuestions');
                    try {
                        if (!this.db) {
                            throw new Error('数据库未初始化');
                        }
                        
                        const stmt = this.db.prepare("SELECT * FROM questions ORDER BY createdAt DESC");
                        this.questions = [];
                        
                        while (stmt.step()) {
                            const row = stmt.getAsObject();
                            try {
                                // 解析选项和正确答案
                                const options = JSON.parse(row.options);
                                let correctAnswer = JSON.parse(row.correctAnswer);
                                
                                if (!Array.isArray(correctAnswer)) {
                                    correctAnswer = [correctAnswer];
                                }
                                
                                this.questions.push({
                                    id: row.id,
                                    type: row.type || 'single',
                                    question: row.question,
                                    options: options,
                                    correctAnswer: correctAnswer,
                                    explanation: row.explanation,
                                    wrongCount: row.wrongCount || 0
                                });
                            } catch (e) {
                                console.error('解析题目出错:', e);
                            }
                        }
                        
                        stmt.free();
                        
                        // 初始化刷题
                        this.initQuiz();
                    } catch (error) {
                        console.error('加载题目失败:', error);
                        this.showNotification('加载题目失败: ' + error.message, 'error');
                    }
                },
                
                // 初始化刷题
                initQuiz() {
                    console.log('initQuiz');
                    try {
                        // 随机排序题目
                        this.shuffledQuestions = [...this.questions].sort(() => Math.random() - 0.5);
                        this.currentQuestionIndex = 0;
                        this.currentQuestion = this.shuffledQuestions[0] || {
                            question: '',
                            type: 'single',
                            options: [],
                            correctAnswer: []
                        };
                        this.userAnswer = [];
                        this.showAnswer = false;
                    } catch (error) {
                        console.error('初始化刷题失败:', error);
                        this.showNotification('初始化刷题失败: ' + error.message, 'error');
                    }
                },
                
                // 检查选项是否被选中
                isOptionSelected(index) {
                    return this.userAnswer.includes(index);
                },
                
                // 检查选项是否为正确答案
                isCorrectAnswer(index) {
                    return this.currentQuestion.correctAnswer.includes(index);
                },
                
                // 选择选项
                selectOption(index) {
                    try {
                        if (!this.showAnswer) {
                            // 单选题逻辑
                            if (this.currentQuestion.type === 'single') {
                                this.userAnswer = [index];
                            } 
                            // 多选题逻辑
                            else {
                                const indexInArray = this.userAnswer.indexOf(index);
                                if (indexInArray === -1) {
                                    this.userAnswer.push(index);
                                } else {
                                    this.userAnswer.splice(indexInArray, 1);
                                }
                            }
                        }
                    } catch (error) {
                        console.error('选择选项失败:', error);
                        this.showNotification('选择选项失败: ' + error.message, 'error');
                    }
                },
                
                // 检查是否可以提交
                canSubmit() {
                    if (!this.currentQuestion) {
                        return false;
                    }
                    if (this.currentQuestion.type === 'single') {
                        return this.userAnswer.length === 1;
                    } else {
                        return this.userAnswer.length > 0;
                    }
                },
                
                // 处理提交
                handleSubmit() {
                    try {
                        console.log('提交答案:', !this.canSubmit() );
                        if (!this.canSubmit()) return;
                        
                        this.showAnswer = true;
                        
                        // 检查答案是否正确
                        let isCorrect = true;
                        
                        // 检查所有正确答案是否都被选中
                        this.currentQuestion.correctAnswer.forEach(answer => {
                            if (!this.userAnswer.includes(answer)) {
                                isCorrect = false;
                            }
                        });
                        
                        // 检查是否有错误答案被选中
                        this.userAnswer.forEach(answer => {
                            if (!this.currentQuestion.correctAnswer.includes(answer)) {
                                isCorrect = false;
                            }
                        });
                        
                        // 如果答案不正确，增加错误次数
                        if (!isCorrect) {
                            this.incrementWrongCount(this.currentQuestion.id);
                        }
                    } catch (error) {
                        console.error('提交答案失败:', error);
                        this.showNotification('提交答案失败: ' + error.message, 'error');
                    }
                },
                
                // 下一题
                nextQuestion() {
                    try {
                        if (this.currentQuestionIndex < this.shuffledQuestions.length - 1) {
                            this.currentQuestionIndex++;
                            this.currentQuestion = this.shuffledQuestions[this.currentQuestionIndex];
                            this.userAnswer = [];
                            this.showAnswer = false;
                        }
                    } catch (error) {
                        console.error('切换到下一题失败:', error);
                        this.showNotification('切换到下一题失败: ' + error.message, 'error');
                    }
                },
                
                // 上一题
                prevQuestion() {
                    try {
                        if (this.currentQuestionIndex > 0) {
                            this.currentQuestionIndex--;
                            this.currentQuestion = this.shuffledQuestions[this.currentQuestionIndex];
                            this.userAnswer = [];
                            this.showAnswer = false;
                        }
                    } catch (error) {
                        console.error('切换到上一题失败:', error);
                        this.showNotification('切换到上一题失败: ' + error.message, 'error');
                    }
                },
                
                // 添加选项
                addOption() {
                    try {
                        if (this.formQuestion.options.length < 6) { // 最多6个选项
                            this.formQuestion.options.push('');
                        }
                    } catch (error) {
                        console.error('添加选项失败:', error);
                        this.showNotification('添加选项失败: ' + error.message, 'error');
                    }
                },
                
                // 移除选项
                removeOption() {
                    try {
                        if (this.formQuestion.options.length > 2) { // 最少2个选项
                            // 如果移除的选项是正确答案，需要同步更新
                            const lastIndex = this.formQuestion.options.length - 1;
                            const answerIndex = this.formQuestion.correctAnswer.indexOf(lastIndex);
                            
                            if (answerIndex !== -1) {
                                this.formQuestion.correctAnswer.splice(answerIndex, 1);
                            }
                            
                            this.formQuestion.options.pop();
                        }
                    } catch (error) {
                        console.error('移除选项失败:', error);
                        this.showNotification('移除选项失败: ' + error.message, 'error');
                    }
                },
                
                // 打开添加题目模态框
                openAddQuestionModal() {
                    try {
                        this.editingQuestion = null;
                        this.formQuestion = {
                            type: 'single',
                            question: '',
                            options: ['', '', '', '', ''], // 默认5个选项
                            correctAnswer: [0], // 单选题默认选择第一个选项作为正确答案
                            explanation: ''
                        };
                        this.questionModalActive = true;
                    } catch (error) {
                        console.error('打开添加题目模态框失败:', error);
                        this.showNotification('打开添加题目窗口失败: ' + error.message, 'error');
                    }
                },
                
                // 打开编辑题目模态框
                openEditQuestionModal(question) {
                    try {
                        this.editingQuestion = question;
                        this.formQuestion = {
                            type: question.type || 'single',
                            question: question.question,
                            options: [...question.options],
                            correctAnswer: [...question.correctAnswer],
                            explanation: question.explanation
                        };
                        this.questionModalActive = true;
                    } catch (error) {
                        console.error('打开编辑题目模态框失败:', error);
                        this.showNotification('打开编辑题目窗口失败: ' + error.message, 'error');
                    }
                },
                
                // 关闭题目模态框
                closeQuestionModal() {
                    try {
                        this.questionModalActive = false;
                    } catch (error) {
                        console.error('关闭题目模态框失败:', error);
                        this.showNotification('关闭窗口失败: ' + error.message, 'error');
                    }
                },
                
                // 保存题目
                saveQuestion() {
                    try {
                        // 验证题目内容
                        if (!this.formQuestion.question) {
                            this.showNotification('请填写题目内容', 'error');
                            return;
                        }
                        
                        // 验证选项
                        const validOptions = this.formQuestion.options.filter(option => option.trim() !== '');
                        if (validOptions.length < 2) {
                            this.showNotification('至少需要填写2个有效选项', 'error');
                            return;
                        }
                        
                        // 验证正确答案
                        if (this.formQuestion.type === 'single') {
                            if (this.formQuestion.correctAnswer.length !== 1) {
                                this.showNotification('单选题必须选择一个正确答案', 'error');
                                return;
                            }
                        } else {
                            if (this.formQuestion.correctAnswer.length < 1) {
                                this.showNotification('多选题必须至少选择一个正确答案', 'error');
                                return;
                            }
                        }
                        
                        // 准备保存的数据
                        const optionsToSave = this.formQuestion.options.filter(option => option.trim() !== '');
                        const correctAnswerStr = JSON.stringify(this.formQuestion.correctAnswer);
                        const optionsStr = JSON.stringify(optionsToSave);
                        
                        if (this.editingQuestion) {
                            // 更新现有题目
                            this.db.run(`
                                UPDATE questions SET 
                                    question = ?, 
                                    options = ?, 
                                    correctAnswer = ?, 
                                    explanation = ?,
                                    type = ? 
                                WHERE id = ?
                            `, [
                                this.formQuestion.question,
                                optionsStr,
                                correctAnswerStr,
                                this.formQuestion.explanation,
                                this.formQuestion.type,
                                this.editingQuestion.id
                            ]);
                            this.showNotification('题目更新成功');
                        } else {
                            // 添加新题目
                            this.db.run(`
                                INSERT INTO questions 
                                    (question, options, correctAnswer, explanation, type) 
                                VALUES (?, ?, ?, ?, ?)
                            `, [
                                this.formQuestion.question,
                                optionsStr,
                                correctAnswerStr,
                                this.formQuestion.explanation,
                                this.formQuestion.type
                            ]);
                            this.showNotification('题目添加成功');
                        }
                        
                        saveDB(this.db);
                        this.loadQuestions();
                        this.closeQuestionModal();
                    } catch (error) {
                        console.error('保存题目失败:', error);
                        this.showNotification('保存题目失败: ' + error.message, 'error');
                    }
                },
                
                // 删除题目
                deleteQuestion(id) {
                    try {
                        if (confirm('确定要删除这道题目吗？')) {
                            this.db.run("DELETE FROM questions WHERE id = ?", [id]);
                            saveDB(this.db);
                            this.loadQuestions();
                            this.showNotification('题目已删除');
                        }
                    } catch (error) {
                        console.error('删除题目失败:', error);
                        this.showNotification('删除题目失败: ' + error.message, 'error');
                    }
                },
                
                // 增加错误次数
                incrementWrongCount(id) {
                    try {
                        this.db.run("UPDATE questions SET wrongCount = COALESCE(wrongCount, 0) + 1 WHERE id = ?", [id]);
                        saveDB(this.db);
                        
                        // 更新本地数据
                        const question = this.questions.find(q => q.id === id);
                        if (question) {
                            question.wrongCount = (question.wrongCount || 0) + 1;
                        }
                    } catch (error) {
                        console.error('增加错误次数失败:', error);
                        this.showNotification('更新错误次数失败: ' + error.message, 'error');
                    }
                },
                
                // 触发文件上传
                triggerFileUpload() {
                    try {
                        document.getElementById('file-upload').click();
                    } catch (error) {
                        console.error('触发文件上传失败:', error);
                        this.showNotification('文件上传失败: ' + error.message, 'error');
                    }
                },
                
                // 处理文件上传
                handleFileUpload(event) {
                    try {
                        const file = event.target.files[0];
                        if (!file) return;
                        
                        const reader = new FileReader();
                        reader.onload = (e) => {
                            try {
                                const content = e.target.result;
                                this.processFileContent(content, file.name);
                            } catch (error) {
                                console.error('处理文件内容失败:', error);
                                this.showNotification('处理文件失败: ' + error.message, 'error');
                            }
                        };
                        reader.onerror = () => {
                            this.showNotification('读取文件失败: ' + reader.error.message, 'error');
                        };
                        reader.readAsText(file);
                        
                        // 重置文件输入，以便可以重复上传同一文件
                        event.target.value = '';
                    } catch (error) {
                        console.error('处理文件上传失败:', error);
                        this.showNotification('文件上传失败: ' + error.message, 'error');
                    }
                },
                
                // 处理文件内容
                processFileContent(content, fileName) {
                    try {
                        let successCount = 0;
                        let totalCount = 0;
                        
                        // 根据文件扩展名选择解析方式
                        if (fileName.endsWith('.csv')) {
                            // 处理CSV格式
                            const lines = content.split(/\r?\n/).filter(line => line.trim() !== '');
                            totalCount = lines.length;
                            
                            lines.forEach((line, index) => {
                                try {
                                    // 跳过表头行
                                    if (index === 0 && line.toLowerCase().includes('题目')) {
                                        return;
                                    }
                                    
                                    // 分割CSV行，处理可能包含逗号的字段
                                    const parts = this.parseCsvLine(line);
                                    
                                    // 基本验证
                                    if (parts.length < 5) { // 题目 + 至少2个选项 + 答案 + 解析
                                        throw new Error(`格式不正确，字段不足`);
                                    }
                                    
                                    // 解析字段
                                    const question = parts[0].trim();
                                    const optionsCount = parts.length - 3; // 总字段数 - 题目 - 答案 - 解析 - 题型
                                    const options = [];
                                    
                                    for (let i = 1; i <= optionsCount; i++) {
                                        if (i < parts.length - 2) { // 确保不越界
                                            options.push(parts[i].trim());
                                        }
                                    }
                                    
                                    // 验证选项数量
                                    if (options.length < 2) {
                                        throw new Error(`至少需要2个选项`);
                                    }
                                    
                                    // 解析题型和正确答案
                                    let type = 'single';
                                    let correctAnswerStr = parts[parts.length - 3].trim();
                                    
                                    // 检查是否有题型字段
                                    if (parts.length >= optionsCount + 4) {
                                        const typeField = parts[parts.length - 2].trim().toLowerCase();
                                        if (typeField === 'multiple') {
                                            type = 'multiple';
                                        }
                                    }
                                    
                                    // 解析正确答案
                                    const answerLetters = correctAnswerStr.split(',').map(a => a.trim());
                                    const correctAnswer = answerLetters.map(letter => {
                                        const index = letter.charCodeAt(0) - 'A'.charCodeAt(0);
                                        if (index < 0 || index >= options.length) {
                                            throw new Error(`正确答案超出选项范围: ${letter}`);
                                        }
                                        return index;
                                    });
                                    
                                    // 验证答案数量与题型是否匹配
                                    if (type === 'single' && correctAnswer.length !== 1) {
                                        throw new Error(`单选题只能有一个正确答案`);
                                    }
                                    
                                    // 解析解析
                                    const explanation = parts[parts.length - 2].trim() || '';
                                    
                                    // 插入数据库
                                    this.db.run(`
                                        INSERT INTO questions 
                                            (question, options, correctAnswer, explanation, type) 
                                        VALUES (?, ?, ?, ?, ?)
                                    `, [
                                        question, 
                                        JSON.stringify(options), 
                                        JSON.stringify(correctAnswer), 
                                        explanation,
                                        type
                                    ]);
                                    
                                    successCount++;
                                } catch (error) {
                                    console.error(`处理第${index + 1}行时出错:`, error.message);
                                }
                            });
                        } else if (fileName.endsWith('.txt')) {
                            // 处理TXT格式 - 支持用户提供的特定格式
                            // 按空行分割题目
                            const questions = content.split(/\r?\n\s*\r?\n/).filter(q => q.trim() !== '');
                            totalCount = questions.length;
                            
                            questions.forEach((questionBlock, index) => {
                                try {
                                    // 解析题目块
                                    const lines = questionBlock.split(/\r?\n/)
                                        .map(line => line.trim())
                                        .filter(line => line !== '');
                                    
                                    if (lines.length < 4) { // 至少需要题目行 + 2个选项 + 答案行
                                        throw new Error(`格式不正确，题目内容不完整`);
                                    }
                                    
                                    // 解析题目行（第一行）
                                    let firstLine = lines[0];
                                    // 移除题目编号（如"3、"）
                                    firstLine = firstLine.replace(/^\d+、/, '').trim();
                                    
                                    // 提取题型（如"[多选]"）
                                    let type = 'single';
                                    let questionText = firstLine;
                                    if (firstLine.includes('[')) {
                                        const typeMatch = firstLine.match(/\[(.+?)\]/);
                                        if (typeMatch && typeMatch[1].includes('多')) {
                                            type = 'multiple';
                                        }
                                        // 移除题型标记
                                        questionText = firstLine.replace(/\s*\[[^\]]+\]\s*/, '').trim();
                                    }
                                    
                                    // 提取选项（寻找以"- 字母："开头的行）
                                    const options = [];
                                    let optionLineIndex = 1;
                                    while (optionLineIndex < lines.length) {
                                        const line = lines[optionLineIndex];
                                        // 匹配选项格式：- A：选项内容
                                        const optionMatch = line.match(/^- [A-Z]：/);
                                        if (optionMatch) {
                                            // 提取选项内容（移除前缀）
                                            const optionContent = line.replace(/^- [A-Z]：/, '').trim();
                                            // 只保留中文部分，移除英文翻译
                                            const chineseOption = optionContent.split(/[A-Za-z(]/)[0].trim();
                                            options.push(chineseOption);
                                            optionLineIndex++;
                                        } else {
                                            break;
                                        }
                                    }
                                    
                                    // 验证选项数量
                                    if (options.length < 2) {
                                        throw new Error(`题目选项不足2个`);
                                    }
                                    
                                    // 解析正确答案
                                    let correctAnswerLine = lines[optionLineIndex];
                                    if (!correctAnswerLine || !correctAnswerLine.includes('正确答案：')) {
                                        throw new Error(`未找到正确答案`);
                                    }
                                    
                                    // 提取正确答案字母
                                    const answerText = correctAnswerLine.replace('正确答案：', '').trim();
                                    const answerLetters = answerText.split(',').map(a => a.trim());
                                    
                                    // 转换为索引（A->0, B->1, 等）
                                    const correctAnswer = answerLetters.map(letter => {
                                        const index = letter.charCodeAt(0) - 'A'.charCodeAt(0);
                                        if (index < 0 || index >= options.length) {
                                            throw new Error(`正确答案超出选项范围: ${letter}`);
                                        }
                                        return index;
                                    });
                                    
                                    // 验证答案数量与题型是否匹配
                                    if (type === 'single' && correctAnswer.length !== 1) {
                                        throw new Error(`单选题只能有一个正确答案`);
                                    }
                                    
                                    // 解析解析部分
                                    let explanation = '';
                                    const explanationLineIndex = optionLineIndex + 1;
                                    if (explanationLineIndex < lines.length && lines[explanationLineIndex].includes('解析：')) {
                                        explanation = lines[explanationLineIndex].replace('解析：', '').trim();
                                    }
                                    
                                    // 插入数据库
                                    this.db.run(`
                                        INSERT INTO questions 
                                            (question, options, correctAnswer, explanation, type) 
                                        VALUES (?, ?, ?, ?, ?)
                                    `, [
                                        questionText, 
                                        JSON.stringify(options), 
                                        JSON.stringify(correctAnswer), 
                                        explanation,
                                        type
                                    ]);
                                    
                                    successCount++;
                                } catch (error) {
                                    console.error(`处理第${index + 1}题时出错:`, error.message);
                                }
                            });
                        }
                        
                        saveDB(this.db);
                        this.loadQuestions();
                        this.showNotification(`导入完成，成功导入 ${successCount} 道题，共 ${totalCount} 道题`);
                    } catch (error) {
                        console.error('处理文件内容失败:', error);
                        this.showNotification('处理文件失败: ' + error.message, 'error');
                    }
                },
                
                // 解析CSV行，处理包含逗号的字段
                parseCsvLine(line) {
                    const parts = [];
                    let currentPart = '';
                    let inQuotes = false;
                    let quoteCount = 0;
                    
                    for (let i = 0; i < line.length; i++) {
                        const char = line[i];
                        
                        if (char === '"') {
                            quoteCount++;
                            // 检查是否是双引号（转义的引号）
                            if (i < line.length - 1 && line[i + 1] === '"') {
                                currentPart += '"';
                                i++; // 跳过下一个引号
                                quoteCount = 0;
                            } else {
                                inQuotes = !inQuotes;
                            }
                        } else if (char === ',' && !inQuotes) {
                            parts.push(currentPart);
                            currentPart = '';
                        } else {
                            currentPart += char;
                        }
                    }
                    
                    // 添加最后一个部分
                    parts.push(currentPart);
                    
                    // 处理可能未闭合的引号
                    if (quoteCount % 2 !== 0) {
                        console.warn('CSV行可能包含未闭合的引号:', line);
                    }
                    
                    return parts;
                },
                
                // 下载导入模板
                downloadTemplate() {
                    try {
                        const templateContent = `题目,选项A,选项B,选项C,选项D,选项E,正确答案(字母，如A,B),解析,题型(single/multiple)
1+1等于几?,0,1,2,3,,A,1+1=2是基本的数学加法,single
Vue.js是什么?,一种水果,JavaScript框架,游戏,操作系统,,B,Vue.js是一套用于构建用户界面的渐进式JavaScript框架,single
以下哪些是前端框架?,Vue.js,React,Java,Angular,,A,B,D,Java是后端语言,multiple`;
                        
                        const blob = new Blob([templateContent], { type: 'text/csv;charset=utf-8;' });
                        const url = URL.createObjectURL(blob);
                        const link = document.createElement('a');
                        link.setAttribute('href', url);
                        link.setAttribute('download', '题目导入模板.csv');
                        link.style.visibility = 'hidden';
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                    } catch (error) {
                        console.error('下载模板失败:', error);
                        this.showNotification('下载模板失败: ' + error.message, 'error');
                    }
                },
                
                // 导出所有题目
                exportQuestions() {
                    try {
                        this.exportToCSV(this.questions, '所有题目');
                    } catch (error) {
                        console.error('导出所有题目失败:', error);
                        this.showNotification('导出题目失败: ' + error.message, 'error');
                    }
                },
                
                // 导出错题
                exportWrongQuestions() {
                    try {
                        const wrongQuestions = this.questions.filter(q => q.wrongCount > 0);
                        this.exportToCSV(wrongQuestions, '错题集');
                    } catch (error) {
                        console.error('导出错题失败:', error);
                        this.showNotification('导出错题失败: ' + error.message, 'error');
                    }
                },
                
                // 导出到CSV
                exportToCSV(questions, fileName) {
                    try {
                        if (questions.length === 0) {
                            this.showNotification('没有可导出的题目', 'error');
                            return;
                        }
                        
                        // 构建CSV表头
                        let csvContent = "题目";
                        // 最多支持6个选项
                        for (let i = 0; i < 6; i++) {
                            csvContent += `,选项${String.fromCharCode(65 + i)}`;
                        }
                        csvContent += ",正确答案(字母),解析,题型,错误次数\n";
                        
                        questions.forEach(question => {
                            // 处理正确答案格式（转换为字母）
                            const correctAnswerLetters = question.correctAnswer.map(index => 
                                String.fromCharCode(65 + index)
                            ).join(',');
                            
                            const row = [question.question];
                            
                            // 添加选项
                            question.options.forEach(option => {
                                row.push(option);
                            });
                            
                            // 填充空白选项
                            for (let i = question.options.length; i < 6; i++) {
                                row.push('');
                            }
                            
                            // 添加其他字段
                            row.push(
                                correctAnswerLetters,
                                question.explanation || '',
                                question.type,
                                question.wrongCount || 0
                            );
                            
                            // 处理包含逗号的字段
                            const escapedRow = row.map(field => {
                                // 确保field是字符串类型
                                const fieldStr = String(field);
                                if (fieldStr.includes(',') || fieldStr.includes('"') || fieldStr.includes('\n')) {
                                    return `"${fieldStr.replace(/"/g, '""')}"`;
                                }
                                return fieldStr;
                            });
                            
                            csvContent += escapedRow.join(',') + "\n";
                        });
                        
                        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
                        const url = URL.createObjectURL(blob);
                        const link = document.createElement('a');
                        link.setAttribute('href', url);
                        link.setAttribute('download', `${fileName}_${new Date().toLocaleDateString()}.csv`);
                        link.style.visibility = 'hidden';
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                        
                        this.showNotification(`成功导出 ${questions.length} 道题`);
                    } catch (error) {
                        console.error('导出到CSV失败:', error);
                        this.showNotification('导出失败: ' + error.message, 'error');
                    }
                },
                
                // 清空所有数据
                clearAllData() {
                    try {
                        if (confirm('确定要清空所有数据吗？此操作不可恢复！')) {
                            this.db.run("DROP TABLE questions");
                            this.db.run(`
                                CREATE TABLE IF NOT EXISTS questions (
                                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                                    question TEXT NOT NULL,
                                    options TEXT NOT NULL,
                                    correctAnswer TEXT NOT NULL,
                                    explanation TEXT,
                                    wrongCount INTEGER DEFAULT 0,
                                    type TEXT DEFAULT 'single',
                                    createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                                )
                            `);
                            saveDB(this.db);
                            this.loadQuestions();
                            this.showNotification('所有数据已清空');
                        }
                    } catch (error) {
                        console.error('清空所有数据失败:', error);
                        this.showNotification('清空数据失败: ' + error.message, 'error');
                    }
                },
                
                // 显示通知
                showNotification(message, type = 'success') {
                    try {
                        this.notification = {
                            active: true,
                            message,
                            type
                        };
                        
                        setTimeout(() => {
                            this.notification.active = false;
                        }, 3000);
                    } catch (error) {
                        console.error('显示通知失败:', error);
                    }
                }
            }
        });
    </script>
    
    <!-- 引入应用逻辑 -->
    <script type="module" src="js/index.js"></script>
</body>
</html>